﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Collections;
using System.Windows.Forms;
using SYcwpb.Models;
using SYcwpb.Helpers;
using System.Collections.ObjectModel;

namespace SYcwpb.Helpers
{
    /// <summary>
    /// 设置便乘人数，顶饭圈人数排交路算法
    /// </summary>
    class GenerateCrossingRoadByBCNum
    {
        private SqlDataLayer sqlHelper = new SqlDataLayer();

        public string lineID;

        private string TableName;

        private int TableID;

        private string FirstID;

        private int bcGarageDelay;

        /// <summary>
        /// 记录是否已经有夜班车开始回库，如果有夜班车回库后，白班电话退勤的交路可以退勤
        /// </summary>
        private bool is_yb_firstback = false;
        private string phoneOutTrain;

        /// <summary>
        /// 夜班顶饭圈交路遇回库车时，是否便乘人员回库
        /// </summary>
        private bool Is_NightMeal_BC = false;

        /// <summary>
        /// 夜班空车的首个车次
        /// </summary>
        private string NightEmptyTrain;
        private ArrayList NightEmptyTrainList = new ArrayList();

        /// <summary>
        /// 非夜班提前便乘退勤集合
        /// </summary>
        private ArrayList UnNightBCOutCollection = new ArrayList();

        private Dictionary<string, ClassType> UnMorningBcCollection = new Dictionary<string, ClassType>();

        private ObservableCollection<EarlyBackGarageModel> EarlyBackGarageCollection = new ObservableCollection<EarlyBackGarageModel>();

        private ObservableCollection<SetMealCrossRoadModel> SetMealCrossRoadCollection = new ObservableCollection<SetMealCrossRoadModel>();

        private ObservableCollection<TrainIdModel> PhoneAttendOutCollection = new ObservableCollection<TrainIdModel>();

        private ObservableCollection<TrainIdModel> UnplanCollection = new ObservableCollection<TrainIdModel>();

        /// <summary>
        /// 便乘到另一终点的车次，1号线为到黎明站，2号线为到三台子站
        /// </summary>
        public ArrayList bc_last_arr;

        /// <summary>
        /// 便乘到第一个站点的车次，1号线为十三号街站，2号线为全运路站
        /// </summary>
        public ArrayList bc_first_arr;

        /// <summary>
        /// 该时刻表所有车次的信息，元素为Train对象，如果某车次已在交路中，将会在该集合中删除
        /// </summary>
        public ArrayList allTrainInfo = new ArrayList();

        /// <summary>
        /// 所有交路的集合
        /// </summary>
        public ArrayList crossingRoadCollections = new ArrayList();

        /// <summary>
        /// 始发方向的候车队列  1 号线为 十三号街队列。2号线为全运路的队列
        /// </summary>
        public List<CrossingRoad> StartQueue = new List<CrossingRoad>();


        /// <summary>
        /// 各个班次的所有车头号集合，用于统计每个班次需要多少个预订交路
        /// 早班：早班的出库车
        /// 白班：早班车中减去9点钟前的回库车，加上白班结束前的出库车
        /// 夜班：白班车中减去4点前的回库车，加上夜班的出库车
        /// </summary>
        public Dictionary<string, ArrayList> ClassTrainList = new Dictionary<string, ArrayList>();

        public int ZBCrossListCount = 0;

        public int BBCrossListCount = 0;

        public int YBCrossListCount = 0;

        /// <summary>
        /// 回库司机的集合
        /// </summary>
        public List<CrossingRoad> GarageCrossList = new List<CrossingRoad>();
        /// <summary>
        /// 终点处的候车队列  1 号线为 黎明广场队列。2号线为三台子队列
        /// </summary>
        public List<CrossingRoad> EndQueue = new List<CrossingRoad>();

        /// <summary>
        /// 早/白班交接班时间
        /// </summary>
        public int int_ChangeTime_ZB;

        /// <summary>
        /// 白/夜班交接班时间
        /// </summary>
        public int int_ChangeTime_BB;

        /// <summary>
        /// 该时间前的出库车由早班司机开出
        /// </summary>
        public int int_ZB_OutTime = 0;

        /// <summary>
        /// 结束时间在9点前的回库车由早班司机直接开回库，然后退勤
        /// </summary>
        public int int_ZB_BackTime = 32400;

        /// <summary>
        /// 下午16点前的出库车都由白班司机开
        /// </summary>
        public int int_BB_OutTime = 57600;

        /// <summary>
        /// 午饭时间
        /// </summary>
        public int int_LunchTime;

        /// <summary>B
        /// 晚饭时间
        /// </summary>
        public int int_SuperTime;

        /// <summary>
        /// 交接班地点，1号线为启工街，2号线为青年大街
        /// </summary>
        public string ChangeStation = "10";

        public const int Up_Direction = 2;

        public const int Down_Direction = 1;

        public int Start_Direction = -1;

        public int Reverse_Direction = -1;

        /// <summary>
        /// 便乘到首站人数
        /// </summary>
        public int BcUpNum { get; set; }

        /// <summary>
        /// 便乘到终点人数
        /// </summary>
        public int BcDownNum { get; set; }

        /// <summary>
        /// 超过该阈值的车，属于下一个班组
        /// </summary>
        public int thresholdValue = 2 * 60 * 60;

        private WriteLog log ;

        public GenerateCrossingRoadByBCNum(ref CrossingRoadParameter parameters)
        {
            InitParameters(parameters);

            if (lineID == "1")
            {
                this.Start_Direction = Up_Direction;
                this.Reverse_Direction = Down_Direction;
            }
            else
            {
                this.Start_Direction = Down_Direction;
                this.Reverse_Direction = Up_Direction;
            }

            InitAllTrainInfo();

            InitClassTrainList();
            
        }

        /// <summary>
        /// 初始化参数
        /// </summary>
        /// <param name="parameters"></param>
        private void InitParameters(CrossingRoadParameter parameters)
        {
            this.lineID = parameters.lineID;

            this.TableID = parameters.TableID;

            this.TableName = parameters.TableName;

            this.FirstID = parameters.FirstID;

            this.phoneOutTrain = parameters.PhoneOutTrain;

            this.UnNightBCOutCollection = parameters.UnNightBCOutCollection;

            this.PhoneAttendOutCollection = parameters.PhoneAttendOutCollections;

            this.UnplanCollection = parameters.UnplanCollection;

            this.NightEmptyTrain = parameters.NightEmptyTrain;

            this.int_ChangeTime_ZB = parameters.int_ChangeTime_ZB;

            this.int_ChangeTime_BB = parameters.int_ChangeTime_BB;

            if (parameters.int_ZB_OutTime < int_ChangeTime_ZB)
                this.int_ZB_OutTime = int_ChangeTime_ZB;
            else
                this.int_ZB_OutTime = parameters.int_ZB_OutTime;

            this.int_ZB_BackTime = parameters.int_ZB_BackTime;

            if (parameters.int_BB_OutTime < int_ChangeTime_BB)
                this.int_BB_OutTime = int_ChangeTime_BB;
            else
                this.int_BB_OutTime = parameters.int_BB_OutTime;

            this.int_LunchTime = parameters.int_LunchTime;

            this.int_SuperTime = parameters.int_SuperTime;

            this.bc_last_arr = parameters.bc_last_arr;

            this.bc_first_arr = parameters.bc_first_arr;

            this.UnMorningBcCollection = parameters.UnMorningBcCollection;

            this.EarlyBackGarageCollection = parameters.EarlyBackGarageCollections;

            this.SetMealCrossRoadCollection = parameters.SetMealCrossRoadCollection;

            this.BcUpNum = parameters.BcUpNum < 0 ? 0 : parameters.BcUpNum;

            this.BcDownNum = parameters.BcDownNum < 0 ? 0 : parameters.BcDownNum;

            this.bcGarageDelay = parameters.BcGarageDelay;
        }

        /// <summary>
        /// 初始化 ArrayList ：allTrainInfo 
        /// </summary>
        private void InitAllTrainInfo()
        {
            WriteLog log = new WriteLog(string.Format("{0}_TrainInfo.txt", TableName));

            string sql_traininfo = "select distinct A.TrainID,A.LastID,B.TBegin,A.Arrive,A.Depart,A.Start,A.Destiny,B.TEnd, DID,(select case when exists (select a1.arc_ne  from [" + TableName + "] as a1 where a1.trainid=a.trainid and a1.arc_ne='#####') then 1 else 0 end) as IsLastTrip from [" + TableName
                + "] A left join TrainDetailInfo B on A.TrainID = B.TrainID   where A.Station = '10' and B.tableInfo_id = '" + TableID + "' order by TBegin";
            DataTable dt_traininfo = sqlHelper.SelectDt(sql_traininfo);
            if (null == dt_traininfo || dt_traininfo.Rows.Count < 1)
            {
                Console.WriteLine("初始化时刻表列车信息失败！");
                return;
            }

            int firstEmptyTrainBeginTime = -1;

            for (int i = 0; i < dt_traininfo.Rows.Count; i++)
            {
                Train train = new Train();
                train.TrainID = dt_traininfo.Rows[i]["TrainID"].ToString();
                train.LastID = dt_traininfo.Rows[i]["LastID"].ToString();

                train.BeginTime = Convert.ToInt32(dt_traininfo.Rows[i]["TBegin"]);
                train.TimeAtChangePoint = Convert.ToInt32(dt_traininfo.Rows[i]["Arrive"].ToString());
                train.TimeLeaveChangePoint = Convert.ToInt32(dt_traininfo.Rows[i]["Depart"].ToString());
                train.EndTime = Convert.ToInt32(dt_traininfo.Rows[i]["TEnd"].ToString());

                train.DID = dt_traininfo.Rows[i]["DID"].ToString();

                if (train.LastID == FirstID) //判别该车是否为出库车
                {
                    train.IsFirstOut = true;
                }

                int start = Convert.ToInt32(dt_traininfo.Rows[i]["Start"].ToString());
                int destiny = Convert.ToInt32(dt_traininfo.Rows[i]["Destiny"].ToString());
                if (Convert.ToBoolean(dt_traininfo.Rows[i]["IsLastTrip"]))
                    train.IsLastTrip = true;
                else
                    train.IsLastTrip = false;
                train.StartID = start;
                train.EndID = destiny;
                train.Init(TableName, start, destiny, lineID);



                string trainLine = (i + 1).ToString() + "  " + train.TrainID + "  " + GlobalVariables.FormatTime(train.BeginTime.ToString()) + "  "
                    + GlobalVariables.FormatTime(train.TimeAtChangePoint.ToString()) + "  " + GlobalVariables.FormatTime(train.EndTime.ToString());
                log.WriteLine(trainLine);

                //夜班回库的空车集合
                if (!string.IsNullOrEmpty(NightEmptyTrain))
                {
                    NightEmptyTrain = NightEmptyTrain.Trim();
                    if (train.TrainID == NightEmptyTrain)
                    {
                        firstEmptyTrainBeginTime = train.BeginTime;
                        NightEmptyTrainList.Add(NightEmptyTrain);
                    }

                    if (firstEmptyTrainBeginTime != -1 && train.BeginTime > firstEmptyTrainBeginTime && train.IsLastTrip)
                        NightEmptyTrainList.Add(train.TrainID);
                }

                allTrainInfo.Add(train);

            }
            log.Close();
        }

        private void InitClassTrainList()
        {
            if (null == allTrainInfo)
                return;
            ClassTrainList.Clear();
            Train train;

            //添加早班车
            ClassTrainList.Add("ZB", new ArrayList());
            for (int i = 0; i < allTrainInfo.Count; i++)
            {
                train = allTrainInfo[i] as Train;
                if (JumpTrain(train.TrainID))
                    continue;
                if (train.IsFirstOut && train.BeginTime < int_ZB_OutTime)
                {
                    ClassTrainList["ZB"].Add(train.GetMidID());
                }
            }
            //添加白班的车
            ClassTrainList.Add("BB", ClassTrainList["ZB"].Clone() as ArrayList);
            ArrayList tempList = ClassTrainList["ZB"].Clone() as ArrayList;

            for (int i = 0; i < tempList.Count; i++)   //去掉9点前回库的车
            {
                string trainMidID = tempList[i].ToString();

                for (int j = 0; j < allTrainInfo.Count; j++)
                {
                    train = allTrainInfo[j] as Train;
                    if (JumpTrain(train.TrainID))
                        continue;
                    if (trainMidID == train.GetMidID() && train.IsLastTrip && train.EndTime < int_ZB_BackTime)
                        ClassTrainList["BB"].Remove(trainMidID);

                    if (i == 0 && train.IsFirstOut && train.BeginTime > int_ZB_OutTime && train.BeginTime < int_BB_OutTime) //只需要执行一遍就够了，所以添加 i==0 的判断条件
                    {
                        if (!ClassTrainList["BB"].Contains(train.GetMidID()))
                            ClassTrainList["BB"].Add(train.GetMidID());
                    }
                }
            }

            //添加夜班的车
            ClassTrainList.Add("YB", ClassTrainList["BB"].Clone() as ArrayList);
            tempList = ClassTrainList["BB"].Clone() as ArrayList;
            for (int i = 0; i < tempList.Count; i++)   //去掉9点前回库的车
            {
                string trainMidID = tempList[i].ToString();

                for (int j = 0; j < allTrainInfo.Count; j++)
                {
                    train = allTrainInfo[j] as Train;
                    if (JumpTrain(train.TrainID))
                        continue;
                    if (trainMidID == train.GetMidID() && train.IsLastTrip && train.EndTime < int_ChangeTime_BB)
                        ClassTrainList["YB"].Remove(trainMidID);

                    if (i == 0 && train.IsFirstOut && train.BeginTime > int_BB_OutTime) //只需要执行一遍就够了，所以添加 i==0 的判断条件
                    {
                        if (!ClassTrainList["YB"].Contains(train.GetMidID()))
                            ClassTrainList["YB"].Add(train.GetMidID());
                    }
                }
            }

            ZBCrossListCount = ClassTrainList["ZB"].Count + bc_first_arr.Count + bc_last_arr.Count;
            BBCrossListCount = ClassTrainList["BB"].Count + bc_first_arr.Count + bc_last_arr.Count;
            YBCrossListCount = ClassTrainList["YB"].Count + bc_first_arr.Count + bc_last_arr.Count;

            foreach (KeyValuePair<string,ClassType> kvp in UnMorningBcCollection)
            {
                if (kvp.Value == ClassType.Day)
                {
                    BBCrossListCount++;
                    YBCrossListCount++;
                }
                else if (kvp.Value == ClassType.Night)
                    YBCrossListCount++;
            }

            WriteLog log = new WriteLog(string.Format("{0}_ClassTrainInfo.txt", TableName));
            foreach (string key in ClassTrainList.Keys)
            {
                ArrayList arrlist = ClassTrainList[key].Clone() as ArrayList;
                log.Write(string.Format("{0} Counts: {1} ", key, arrlist.Count));
                for (int i = 0; i < arrlist.Count; i++)
                {
                    log.Write(string.Format(" {0}  ", arrlist[i] as string));
                }
                log.WriteLine("");
            }
            log.Close();
        }
        bool JumpTrain(String trainid)
        {
            foreach (var item in UnplanCollection)
            {
                if (item.TrainId == trainid)
                {
                    return true;
                }

            }
            return false;
        }
        public GenerateCrossingRoadResultType Generate2()
        {
            Helpers.SYCWPBGlobalvariables.globalvariables.log.writeInfo("开始生成交路的逻辑");
            try
            {
                GenerateCrossingRoadResultType result = GenerateCrossingRoadResultType.Success;

                QueueCompare queueCompare = new QueueCompare();

                ClassType _currentClass = ClassType.Morning;

                int bcCount = 0;

                int trainLeft = allTrainInfo.Count;

                for (int i = 0; i < allTrainInfo.Count; i++)
                {
                    Train train = allTrainInfo[i] as Train;
                    

                    if (JumpTrain(train.TrainID))
                        continue;
                    if (NightEmptyTrainList.Contains(train.TrainID))  //如果在空车集合中，因为已经被提前接走，所以不用执行循环
                        continue;
                    bool phoneAttendOut = false;
                    foreach (var item in PhoneAttendOutCollection)
                    {
                        if (!string.IsNullOrEmpty(item.TrainId) && train.TrainID == item.TrainId)
                            phoneAttendOut = true;
                    }
                    if (train.Direction == Start_Direction)
                    {

                        bool canRemove = false;
                        bool isEmptyBackGarage = false;
                        CrossingRoad currentRoad;

                        if (StartQueue.Count == 0 || train.IsFirstOut)
                        {
                            ClassType classT;

                            if (train.BeginTime < int_ZB_OutTime)
                                classT = ClassType.Morning;
                            else if (train.BeginTime < int_BB_OutTime)
                                classT = ClassType.Day;
                            else
                                classT = GetClassFromFisrtOutTrain(train.BeginTime);

                            currentRoad = GetCrossingRoad(classT, train.IsFirstOut, AttendOutPlace.Garage, train.BeginTime);

                            if (!string.IsNullOrEmpty(phoneOutTrain) && train.TrainID == phoneOutTrain)
                                currentRoad.is_bb_phoneout = true;



                            #region 交路数预分批异常
                            if (null == currentRoad)
                            {
                                if (classT == ClassType.Morning)
                                    result = GenerateCrossingRoadResultType.LackDriver_ZB;
                                else if (classT == ClassType.Day)
                                    result = GenerateCrossingRoadResultType.LackDriver_BB;
                                else
                                    result = GenerateCrossingRoadResultType.LackDriver_YB;
                                return result;
                            }
                            #endregion
                        }
                        else
                        {
                            currentRoad = StartQueue[0];
                            canRemove = true;
                        }
                        if (phoneAttendOut)
                            currentRoad.is_bb_phoneout = true;
                        //夜班顶饭圈遇到回库车的逻辑在夜班回库车处理中
                        while (currentRoad.is_meal_road && currentRoad.Items.Count >= 2 && !currentRoad.isMealRoadContinue)   //顶饭圈的交路只跑一圈，夜班顶饭圈继续值勤的除外
                        {
                            if (currentRoad.GetLastTrain().IsLastTrip)
                                currentRoad._OutPlace = AttendOutPlace.Garage;
                            else
                                currentRoad._OutPlace = AttendOutPlace.FirSta;

                            currentRoad.EndTime = currentRoad.GetLastTrain().EndTime;
                            crossingRoadCollections.Add(currentRoad);    //顶完饭圈就退出轮换
                            StartQueue.RemoveAt(0);

                            currentRoad = StartQueue[0];

                            canRemove = true;
                        }

                        // 由于始发方向不存在不同地点接车不上的问题，所以先不考虑
                        currentRoad.Add(train);
                        //if (lineID == "2" && i == 0 && train.EndPlace != AttendOutPlace.STZSta) //2号线首班车到三台子的，是便乘到空航天大去,以后如果无此业务，可删除，保留esle部分即可  Modifed by ply 2013/12/13
                        //    currentRoad._CurrnetPlace = AttendOutPlace.LastSta;
                        //else
                            currentRoad._CurrnetPlace = train.EndPlace;
                        currentRoad.availableTime = train.EndTime;

                        string nextTrainID = train.GetNextTrain();

                        if (UnNightBCOutCollection.Contains(nextTrainID)) //非夜班便乘退勤逻辑
                        {
                            if (!currentRoad.is_meal_road && !currentRoad.is_bb_phoneout)
                            {
                                Train nextT = null;
                                if (CheckTrainExists(i, nextTrainID, ref nextT))
                                {
                                    currentRoad.EndTime = nextT.TimeAtChangePoint;
                                    currentRoad._OutPlace = AttendOutPlace.MidSta;
                                    currentRoad.BCBackGarageTrainID = nextTrainID;
                                    crossingRoadCollections.Add(currentRoad);

                                    isEmptyBackGarage = true;
                                    canRemove = true;
                                }
                            }
                        }

                        if (NightEmptyTrainList.Contains(nextTrainID)) //夜班空车的处理
                        {
                            Train emptyTrain = null;
                            if (CheckLastTrainExists(i, nextTrainID, ref emptyTrain))
                            {
                                currentRoad.Add(emptyTrain);

                                currentRoad._OutPlace = AttendOutPlace.Garage;
                                currentRoad.EndTime = emptyTrain.EndTime;
                                crossingRoadCollections.Add(currentRoad);

                                canRemove = true;
                                isEmptyBackGarage = true;
                            }
                        }

                        if (currentRoad.is_meal_road && currentRoad.BeginTime == -1) //顶饭圈交路首次接车
                        {
                            currentRoad.BeginTime = train.BeginTime;
                        }

                        if (GetBCTrain(bc_last_arr, train.TrainID, ref bcCount))    //插入一个便乘交路
                        {
                            //2号线多个交路便乘首班车到达三台子的，仅保留一个交路由三台子发车即可，以后如无此需求，还原注释部分，删除当前的代码即可 Modifed by ply 2013/12/13
                            bool isBcSTZ = false;
                            //for (int k = 0; k < bcCount; k++)
                            //{
                            //    CrossingRoad bcRoad = GetCrossingRoad(ClassType.Morning, false, AttendOutPlace.Garage, train.BeginTime);

                            //    if (null == bcRoad)
                            //        return result = GenerateCrossingRoadResultType.LackDriver_ZB;

                            //    bcRoad.is_bc_last = true;
                            //    bcRoad.bc_train = train;
                            //    bcRoad._CurrnetPlace = train.EndPlace;

                            //    if (lineID == "2" && i == 0 && train.EndPlace == AttendOutPlace.STZSta)
                            //    {
                            //        if (isBcSTZ)
                            //            bcRoad._CurrnetPlace = AttendOutPlace.LastSta;
                            //        else
                            //        {
                            //            isBcSTZ = true; //留一个便乘的交路从三台子返回
                            //        }
                            //    }

                            //    EndQueue.Add(bcRoad);
                            //}

                            for (int k = 0; k < bcCount; k++)
                            {
                                CrossingRoad bcRoad = GetCrossingRoad(ClassType.Morning, false, AttendOutPlace.Garage, train.BeginTime);

                                if (null == bcRoad)
                                    return result = GenerateCrossingRoadResultType.LackDriver_ZB;

                                bcRoad.is_bc_last = true;
                                bcRoad.bc_train = train;
                                bcRoad._CurrnetPlace = train.EndPlace;

                                EndQueue.Add(bcRoad);
                            }

                            bcCount = 0;
                        }
                        if (GetBCTrain(bc_first_arr, train.TrainID, ref bcCount))
                        {
                            for (int k = 0; k < bcCount; k++)
                            {
                                CrossingRoad bcroad = GetCrossingRoad(ClassType.Morning, false, AttendOutPlace.Garage, train.BeginTime);

                                if (null == bcroad)
                                    return result = GenerateCrossingRoadResultType.LackDriver_ZB;

                                bcroad.is_bc_first = true;
                                bcroad.bc_train = train;
                                bcroad._CurrnetPlace = train.EndPlace;

                                StartQueue.Add(bcroad);
                            }
                            bcCount = 0;
                        }
                        if (UnMorningBcCollection.ContainsKey(train.TrainID)) //白班便乘出勤的逻辑
                        {
                            ClassType tempCls;
                            if (UnMorningBcCollection.TryGetValue(train.TrainID, out tempCls))
                            {
                                CrossingRoad bcRoad = GetCrossingRoad(tempCls, false, AttendOutPlace.MidSta, train.TimeLeaveChangePoint);

                                if (null == bcRoad)
                                    return result = GenerateCrossingRoadResultType.LackDriver;

                                bcRoad.is_bc_last = true;
                                bcRoad.bc_train = train;
                                bcRoad._CurrnetPlace = train.EndPlace;
                                bcRoad.availableTime = train.EndTime - 1;  //便乘的需要排在开车的前面
                                bcRoad.can_jumpQueue = true;

                                EndQueue.Add(bcRoad);
                            }
                        }

                        if (currentRoad.is_bb_phoneout)  //白班电话退勤交路的处理
                        {
                            //if (is_yb_firstback)
                            {
                                currentRoad._OutPlace = AttendOutPlace.LastSta;
                                currentRoad.EndTime = currentRoad.GetLastTrain().EndTime;

                                crossingRoadCollections.Add(currentRoad);

                                StartQueue.RemoveAt(0);
                                continue;
                            }
                        }

                        if (canRemove)
                        {
                            StartQueue.RemoveAt(0);
                        }

                        if (!ChangeToNextClass(train, ref currentRoad, ref _currentClass, ref result))
                            return result;

                        if (!isEmptyBackGarage) //如果是最后空车回去的话，就不用在加入到另一队列
                            EndQueue.Add(currentRoad);
                    }
                    else
                    {
                        bool canInsert = true;

                        if (EndQueue.Count == 0)
                        {
                            CrossingRoad newRoad = GetCrossingRoad(_currentClass, false, AttendOutPlace.LastSta, train.BeginTime);

                            #region 交路数预分批异常
                            if (null == newRoad)
                            {
                                if (_currentClass == ClassType.Morning)
                                    result = GenerateCrossingRoadResultType.LackDriver_ZB;
                                else if (_currentClass == ClassType.Day)
                                    result = GenerateCrossingRoadResultType.LackDriver_BB;
                                else
                                    result = GenerateCrossingRoadResultType.LackDriver_YB;
                                return result;
                            }
                            #endregion

                            EndQueue.Add(newRoad);
                        }

                        CrossingRoad downRoad = null;
                        for (int index = 0; index < EndQueue.Count; index++)
                        {
                            if (EndQueue[index]._CurrnetPlace == train.StartPlace && EndQueue[index].availableTime <= train.BeginTime)
                            {
                                downRoad = EndQueue[index];
                                EndQueue.RemoveAt(index);
                                break;
                            }
                            else
                                continue;
                        }

                        if (null == downRoad)
                        {
                            result = GenerateCrossingRoadResultType.LackDriver;
                            return result;
                        }
                        if (phoneAttendOut)
                            downRoad.is_bb_phoneout = true;
                        //CrossingRoad downRoad = EndQueue[0];

                        //if (downRoad.availableTime > train.BeginTime)  //这里是有可能出现接不上车的情况的，但是暂不处理
                        //    ;
                        //else
                        //    EndQueue.RemoveAt(0);

                        downRoad.Add(train);
                        downRoad._CurrnetPlace = train.EndPlace;
                        downRoad.availableTime = train.EndTime;

                        string nextTrainID = train.GetNextTrain();

                        if (UnNightBCOutCollection.Contains(nextTrainID)) //非夜班便乘退勤逻辑
                        {
                            if (!downRoad.is_meal_road && !downRoad.is_bb_phoneout)
                            {
                                Train nextT = null;
                                if (CheckTrainExists(i, nextTrainID, ref nextT))
                                {
                                    downRoad.EndTime = nextT.TimeAtChangePoint;
                                    downRoad._OutPlace = AttendOutPlace.MidSta;
                                    downRoad.BCBackGarageTrainID = nextTrainID;
                                    crossingRoadCollections.Add(downRoad);
                                }

                                canInsert = false;
                            }
                        }

                        MealCrossRoadModel mealroad = null;
                        while (train.EndTime > int_LunchTime && CheckMealCrossRoad(out mealroad,0))
                        {
                            CrossingRoad luncrossoad = new CrossingRoad(ClassType.Day, AttendOutPlace.FirSta);
                            luncrossoad.is_meal_road = true;
                            luncrossoad.availableTime = train.EndTime;
                            luncrossoad._CurrnetPlace = AttendOutPlace.FirSta;
                            StartQueue.Add(luncrossoad);
                        }

                        while (train.EndTime > int_SuperTime && CheckMealCrossRoad(out mealroad, 1))
                        {
                            if (null != mealroad)
                            {
                                CrossingRoad suppcrossoad = new CrossingRoad(ClassType.Night, AttendOutPlace.FirSta);
                                suppcrossoad.is_meal_road = true;
                                suppcrossoad.isMealRoadBcBack = mealroad.IsBcBack;
                                suppcrossoad.isMealRoadContinue = mealroad.IsContinue;
                                suppcrossoad.availableTime = train.EndTime;
                                suppcrossoad._CurrnetPlace = AttendOutPlace.FirSta;

                                StartQueue.Add(suppcrossoad);
                            }
                        }

                        if (UnMorningBcCollection.ContainsKey(train.TrainID)) //白班便乘出勤的逻辑
                        {
                            ClassType tempCls;
                            if (UnMorningBcCollection.TryGetValue(train.TrainID, out tempCls))
                            {
                                CrossingRoad bcRoad = GetCrossingRoad(tempCls, false, AttendOutPlace.MidSta, train.TimeLeaveChangePoint);

                                if (null == bcRoad)
                                    return result = GenerateCrossingRoadResultType.LackDriver;

                                bcRoad.is_bc_first = true;
                                bcRoad.bc_train = train;
                                bcRoad.availableTime = train.EndTime - 1;  //便乘的需要排在开车的前面
                                bcRoad._CurrnetPlace = train.EndPlace;
                                bcRoad.can_jumpQueue = true;

                                StartQueue.Add(bcRoad);
                            }
                        }

                        if (downRoad.is_bb_phoneout) // 白班电话退勤交路不参与交接班
                        {
                            if (is_yb_firstback)  //如果有夜班车回库了，白班电话退勤交路可以退勤了
                            {
                                downRoad._OutPlace = AttendOutPlace.FirSta;
                                downRoad.EndTime = downRoad.GetLastTrain().EndTime;
                                crossingRoadCollections.Add(downRoad);

                                canInsert = false;
                            }
                        }
                        else if (!ChangeToNextClass(train, ref downRoad, ref _currentClass, ref result))
                            return result;

                        Train currentLastT = null;
                        if (null != downRoad)
                            currentLastT = downRoad.GetLastTrain();

                        if (currentLastT != null && currentLastT.IsLastTrip)
                        {
                            canInsert = false;

                            //夜班回库车,
                            if (currentLastT.EndTime > int_ChangeTime_BB)
                            {
                                downRoad._OutPlace = AttendOutPlace.Garage;
                                downRoad.EndTime = downRoad.GetLastTrain().EndTime;
                                crossingRoadCollections.Add(downRoad);

                                if (downRoad.is_meal_road && downRoad.isMealRoadBcBack) // 如果夜班顶饭圈的刚好遇上回库车，此处在首站便乘一组回库
                                {
                                    int canPickT = currentLastT.EndTime - 3 * 60;
                                    PickRoadFromQueue(AttendOutPlace.FirSta, canPickT, 1, currentLastT,true);
                                }
                                else
                                    //此处加入夜班便乘提前回库的逻辑
                                    EarlyBackGarageMethod(ref currentLastT);

                                is_yb_firstback = true;  //有夜班车回库，此时白班电话退勤的司机可以退勤了
                            }
                            else
                            {
                                GarageCrossList.Add(downRoad);
                            }
                        }
                        if (canInsert && null != downRoad)
                        {
                            StartQueue.Add(downRoad);
                        }
                    }

                    StartQueue.Sort(queueCompare);     //由于有转备用的情况，所以要按可以接车的时间进行排序
                    EndQueue.Sort(queueCompare);     //由于有转备用的情况，所以要按可以接车的时间进行排序
                }

                if (result == GenerateCrossingRoadResultType.Success)
                    InitCrossRoadCollections();

                return result;
            }
            catch(Exception ex)
            {
                Helpers.SYCWPBGlobalvariables.globalvariables.log.writeError(ex.ToString());
                return GenerateCrossingRoadResultType.UnKnownError;
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="mealRoad"></param>
        /// <param name="mealT">0：午饭；1：晚饭</param>
        /// <returns></returns>
        private bool CheckMealCrossRoad(out MealCrossRoadModel mealRoad, int mealT)
        {
            string mealTime = mealT == 0 ? "午饭" : "晚饭";

            foreach(SetMealCrossRoadModel setRoad in this.SetMealCrossRoadCollection)
            {
                if (!setRoad.IsUsed && setRoad.MealTime == mealTime)
                {
                    mealRoad = new MealCrossRoadModel();
                    mealRoad.Mealtime = setRoad.MealTime;
                    mealRoad.IsBcBack = setRoad.Is_NightMeal_BC;
                    mealRoad.IsContinue = setRoad.Is_Continue;

                    setRoad.IsUsed = true;

                    return true;
                }
            }

            mealRoad = null;
            return false;
        }

        /// <summary>
        /// 夜班提前便乘回库
        /// </summary>
        /// <param name="road"></param>
        /// <param name="BackTrainID"></param>
        private void EarlyBackGarageMethod(ref Train BackTrain)
        {
            int CanPickTime; //可便乘回去的时间

            foreach (EarlyBackGarageModel earlyBackItem in  EarlyBackGarageCollection)
            {
                if (BackTrain.TrainID == earlyBackItem.TrainID)
                {
                    if (earlyBackItem.StationSelected.attendOutPlace == AttendOutPlace.FirSta)
                        CanPickTime = BackTrain.EndTime - bcGarageDelay; //回库时间大概是三分钟
                    else
                        CanPickTime = BackTrain.BeginTime;

                    PickRoadFromQueue(earlyBackItem.StationSelected.attendOutPlace,CanPickTime, earlyBackItem.Num,BackTrain,true);
                }
            }
        }

        /// <summary>
        /// 从两头队列尾部开始取出指定数量的交路，并放进回库的集合中，顶饭圈交路会被排除在外
        /// </summary>
        private void PickRoadFromQueue(AttendOutPlace pickPlace, int canPickTime, int count, Train BackTrain,bool IsBackGarage)
        {
            if (null == BackTrain)
                return;

            int CanPickLeft = count;

            if (pickPlace == AttendOutPlace.FirSta)
            {
                for (int i = StartQueue.Count - 1; i > -1 && CanPickLeft > 0; i-- )
                {
                    if (StartQueue[i].Items.Count == 0 || StartQueue[i].GetLastTrain().EndTime > canPickTime || StartQueue[i].is_bb_phoneout || StartQueue[i].is_meal_road)
                        continue;

                    CrossingRoad road = StartQueue[i];

                    //回库处理

                    if (IsBackGarage)
                    {
                        road.EndTime = BackTrain.EndTime;
                        road._OutPlace = AttendOutPlace.Garage;
                    }
                    else
                    {
                        road.EndTime = BackTrain.TimeAtChangePoint;
                        road._OutPlace = AttendOutPlace.MidSta;
                    }

                    road.BCBackGarageTrainID = BackTrain.TrainID;

                    crossingRoadCollections.Add(road);

                    StartQueue.RemoveAt(i);
                    CanPickLeft--;
                }
            }
            else
            {
                for (int i = EndQueue.Count - 1; i > -1 && CanPickLeft > 0; i--)
                {
                    if (EndQueue[i].Items.Count == 0 || EndQueue[i].GetLastTrain().EndTime > canPickTime || EndQueue[i].is_meal_road || EndQueue[i].is_bb_phoneout || EndQueue[i]._CurrnetPlace != pickPlace)
                        continue;

                    CrossingRoad road = EndQueue[i];

                    //回库处理
                    if (IsBackGarage)
                    {
                        road.EndTime = BackTrain.EndTime;
                        road._OutPlace = AttendOutPlace.Garage;
                    }
                    else
                    {
                        road.EndTime = BackTrain.TimeAtChangePoint;
                        road._OutPlace = AttendOutPlace.MidSta;
                    }
                    road.BCBackGarageTrainID = BackTrain.TrainID;

                    crossingRoadCollections.Add(road);

                    EndQueue.RemoveAt(i);
                    CanPickLeft--;
                }
            }
        }

        /// <summary>
        /// 从两头队列头部开始取出指定数量的交路，并放进回库的集合中，顶饭圈交路会被排除在外
        /// </summary>
        //private void PickRoadFromQueueStart(AttendOutPlace pickPlace, int canPickTime, int count, Train BackTrain, bool IsBackGarage)
        //{
        //    if (null == BackTrain)
        //        return;

        //    int CanPickLeft = count;

        //    if (pickPlace == AttendOutPlace.FirSta)
        //    {
        //        for (int i = 0; i < StartQueue.Count - 1 && CanPickLeft > 0; i++)
        //        {
        //            if (StartQueue[i].Items.Count == 0 || StartQueue[i].GetLastTrain().EndTime > canPickTime || StartQueue[i].is_bb_phoneout)
        //                continue;

        //            CrossingRoad road = StartQueue[i];

        //            //回库处理

        //            if (IsBackGarage)
        //            {
        //                road.EndTime = BackTrain.EndTime;
        //                road._OutPlace = AttendOutPlace.Garage;
        //            }
        //            else
        //            {
        //                road.EndTime = BackTrain.TimeAtChangePoint;
        //                road._OutPlace = AttendOutPlace.MidSta;
        //            }

        //            road.BCBackGarageTrainID = BackTrain.TrainID;

        //            crossingRoadCollections.Add(road);

        //            StartQueue.RemoveAt(i);
        //            CanPickLeft--;
        //        }
        //    }
        //    else
        //    {
        //        for (int i = 0; i < StartQueue.Count - 1 && CanPickLeft > 0; i++)
        //        {
        //            if (StartQueue[i].Items.Count == 0 || EndQueue[i].GetLastTrain().EndTime > canPickTime || EndQueue[i].is_meal_road || StartQueue[i].is_bb_phoneout)
        //                continue;

        //            CrossingRoad road = EndQueue[i];

        //            //回库处理
        //            if (IsBackGarage)
        //            {
        //                road.EndTime = BackTrain.EndTime;
        //                road._OutPlace = AttendOutPlace.Garage;
        //            }
        //            else
        //            {
        //                road.EndTime = BackTrain.TimeAtChangePoint;
        //                road._OutPlace = AttendOutPlace.MidSta;
        //            }
        //            road.BCBackGarageTrainID = BackTrain.TrainID;

        //            crossingRoadCollections.Add(road);

        //            EndQueue.RemoveAt(i);
        //            CanPickLeft--;
        //        }
        //    }
        //}

        /// <summary>
        /// 从startIndex起  返回上下行方向剩下的车辆数
        /// </summary>
        /// <param name="direc"></param>
        /// <returns></returns>
        private int GetLeftTrainCount(int startIndex,int direc)
        {
            int count = 0;
            Train train = null;
            for (int i = startIndex + 1; i < allTrainInfo.Count;i ++ )
            {
                train = allTrainInfo[i] as Train;
                if (train.Direction == direc)
                {
                    count++;
                }
            }

            return count;
        }

        /// <summary>
        /// 从指定的startIndex起，检索是否有trainID 的回库车次存在
        /// </summary>
        /// <param name="startIndex"></param>
        /// <param name="trainID"></param>
        /// <returns></returns>
        private bool CheckLastTrainExists(int startIndex,string trainID,ref Train nextTrain)
        {
            bool result = false;
            Train train = null;
            for (int i = startIndex + 1; i < allTrainInfo.Count; i++)
            {
                train = allTrainInfo[i] as Train;
                if (train.TrainID == trainID && train.IsLastTrip)
                {
                    nextTrain = train;
                    result = true;

                    break;
                }
            }

            return result;
        }

        /// <summary>
        /// 从指定的startIndex起，检索是否有trainID 的非回库车次存在
        /// </summary>
        /// <param name="startIndex"></param>
        /// <param name="trainID"></param>
        /// <returns></returns>
        private bool CheckTrainExists(int startIndex, string trainID, ref Train nextTrain)
        {
            bool result = false;
            Train train = null;
            for (int i = startIndex + 1; i < allTrainInfo.Count; i++)
            {
                train = allTrainInfo[i] as Train;
                if (train.TrainID == trainID)
                {
                    nextTrain = train;
                    result = true;

                    break;
                }
            }

            return result;
        }

        /// <summary>
        /// 返回从startIndex 开始的最近一个回库车
        /// </summary>
        /// <param name="startIndex"></param>
        /// <param name="?"></param>
        /// <returns></returns>
        private bool GetNextGarageTrain(int startIndex, ref Train nextTrain)
        {
            bool result = false;
            Train train = null;
            var currentTrain=allTrainInfo[startIndex] as Train;
            for (int i = startIndex + 1; i < allTrainInfo.Count; i++)
            {
                train = allTrainInfo[i] as Train;
                
                if (train.IsLastTrip && (train.TimeAtLstSta > currentTrain.TimeAtLstSta+bcGarageDelay))
                {
                    nextTrain = train;
                    result = true;

                    break;
                }
            }

            return result;
        }

        /// <summary>
        /// 返回是否存在bc的车次，引用返回便乘的次数
        /// </summary>
        /// <param name="count"></param>
        /// <returns></returns>
        private bool GetBCTrain(ArrayList bcTrainList,string bcTrain,ref int count)
        {
            bool result = false;

            if (null == bcTrainList || bcTrainList.Count < 1)
            {
                return result;
            }

            for (int i = 0; i < bcTrainList.Count; i ++ )
            {
                if (bcTrainList[i] as string == bcTrain)
                {
                    count++;
                    result = true;
                }
            }

            return result;
        }


        /// <summary>
        /// 根据出库车的开始时间来决定从早白夜的哪个交路集合中取出新的一个交路
        /// </summary>
        /// <param name="timeInt"></param>
        /// <returns></returns>
        private ClassType GetClassFromFisrtOutTrain(int timeInt)
        {
            if (timeInt < int_ZB_OutTime)
                return ClassType.Morning;
            else if (timeInt < int_BB_OutTime)
                return ClassType.Day;
            else
                return ClassType.Night;
        }

        /// <summary>
        /// 换班逻辑
        /// </summary>
        /// <param name="train"></param>
        /// <param name="currentRoad"></param>
        private bool ChangeToNextClass(Train train, ref CrossingRoad currentRoad, ref ClassType _currentClass,ref GenerateCrossingRoadResultType resultType)
        {
            bool isChangeSuccess = true;

            if (train.TimeAtChangePoint > int_ChangeTime_ZB && currentRoad._ClassType == ClassType.Morning)   //早班换白班逻辑
            {
                //此处加入非夜班便乘退勤异常报错
                if (UnNightBCOutCollection.Contains(train.GetNextTrain()))
                {
                    resultType = GenerateCrossingRoadResultType.UnNightBCOutErr;
                    return false;
                }

                _currentClass = ClassType.Day;

                if (train.EndTime < int_ZB_BackTime && train.IsLastTrip)  //9点钟前回库的早班车，不用让白班交路去接
                {
                    currentRoad.EndTime = train.EndTime;
                    currentRoad._OutPlace = AttendOutPlace.Garage;
                    crossingRoadCollections.Add(currentRoad);

                    currentRoad = null;
                    return isChangeSuccess;
                }
                currentRoad.EndTime = train.TimeAtChangePoint;
                currentRoad._OutPlace = AttendOutPlace.MidSta;
                crossingRoadCollections.Add(currentRoad);

                currentRoad = GetCrossingRoad(_currentClass, false, AttendOutPlace.MidSta,train.TimeLeaveChangePoint);

                if (null != currentRoad)
                {
                    currentRoad.Add(train);
                    currentRoad._CurrnetPlace = train.EndPlace;
                    currentRoad.availableTime = train.EndTime;
                }
                else
                    isChangeSuccess = false;
                
            }
            else if (train.TimeAtChangePoint > int_ChangeTime_BB && currentRoad._ClassType == ClassType.Day)
            {
                if (!currentRoad.is_bb_phoneout)  //如果是白班电话退勤的，不需要执行交换
                {
                    //此处加入非夜班便乘退勤异常报错
                    if (UnNightBCOutCollection.Contains(train.GetNextTrain()))
                    {
                        resultType = GenerateCrossingRoadResultType.UnNightBCOutErr;
                        return false;
                    }

                    _currentClass = ClassType.Night;

                    currentRoad.EndTime = train.TimeAtChangePoint;
                    currentRoad._OutPlace = AttendOutPlace.MidSta;
                    crossingRoadCollections.Add(currentRoad);

                    currentRoad = GetCrossingRoad(_currentClass, false, AttendOutPlace.MidSta, train.TimeLeaveChangePoint);

                    if (null != currentRoad)
                    {
                        currentRoad.Add(train);
                        currentRoad._CurrnetPlace = train.EndPlace;
                        currentRoad.availableTime = train.EndTime;
                    }
                    else
                        isChangeSuccess = false;
                }
            }
            if (!isChangeSuccess)
            {
                #region 交路数预分批异常
                if (null == currentRoad)
                {
                    if (_currentClass == ClassType.Morning)
                        resultType = GenerateCrossingRoadResultType.LackDriver_ZB;
                    else if (_currentClass == ClassType.Day)
                        resultType = GenerateCrossingRoadResultType.LackDriver_BB;
                    else
                        resultType = GenerateCrossingRoadResultType.LackDriver_YB;
                }
                #endregion
            }

            return isChangeSuccess;
        }

        /// <summary>
        /// 先从回库的交路里选择，如空，则新建一个交路
        /// </summary>
        /// <param name="_classType"></param>
        /// <param name="isTrainFirstOut"></param>
        /// <returns></returns>
        private CrossingRoad GetCrossingRoad(ClassType _classType, bool isTrainFirstOut,AttendOutPlace attenPlace,int beginT)
        {
            CrossingRoad road = null;

            if (_classType == ClassType.Morning)
            {
                // 由于不用从回库的司机中接出库车，所以注释
                //if (isTrainFirstOut)
                //{
                //    road = GetCrossingRoadFromGarage(_classType);
                //    if (null == road && ZBCrossListCount > 0)
                //    {
                //        road = new CrossingRoad(_classType, attenPlace, beginT);
                //        ZBCrossListCount--;
                //    }
                //}
                //else
                //{
                //    if (ZBCrossListCount > 0)
                //    {
                //        road = new CrossingRoad(_classType, attenPlace, beginT);
                //        ZBCrossListCount--;
                //    }
                //}
                if (ZBCrossListCount > 0)
                {
                    road = new CrossingRoad(_classType, attenPlace, beginT);
                    ZBCrossListCount--;
                }
            }
            else if (_classType == ClassType.Day)
            {
                // 由于不用从回库的司机中接出库车，所以注释
                //if (isTrainFirstOut) 
                //{
                //    road = GetCrossingRoadFromGarage(_classType);
                //    if (null == road && BBCrossListCount > 0)
                //    {
                //        road = new CrossingRoad(_classType, attenPlace, beginT);
                //        BBCrossListCount--;
                //    }
                //}
                //else
                //{
                //    if (BBCrossListCount > 0)
                //    {
                //        road = new CrossingRoad(_classType, attenPlace, beginT);
                //        BBCrossListCount--;
                //    }
                    
                //}
                if (BBCrossListCount > 0)
                {
                    road = new CrossingRoad(_classType, attenPlace, beginT);
                    BBCrossListCount--;
                }
            }
            else if (_classType == ClassType.Night)
            {
                // 由于不用从回库的司机中接出库车，所以注释
                //if (isTrainFirstOut)
                //{
                //    road = GetCrossingRoadFromGarage(_classType);
                //    if (null == road && YBCrossListCount > 0)
                //    {
                //        road = new CrossingRoad(_classType, attenPlace, beginT);
                //        YBCrossListCount--;
                //    }
                //}
                //else
                //{
                //    if (YBCrossListCount > 0)
                //    {
                //        road = new CrossingRoad(_classType, attenPlace, beginT);
                //        YBCrossListCount--;
                //    }
                //}
                if (YBCrossListCount > 0)
                {
                    road = new CrossingRoad(_classType, attenPlace, beginT);
                    YBCrossListCount--;
                }
            }

            return road;
        }

        private CrossingRoad GetCrossingRoadFromGarage(ClassType _classType)
        {
            for (int i = 0; i < GarageCrossList.Count; i++)
            {
                CrossingRoad road = GarageCrossList[i] as CrossingRoad;
                if (road._ClassType == _classType)
                {
                    GarageCrossList.RemoveAt(i);

                    return road;
                }
            }

            return null;
        }


        private void InitCrossRoadCollections()
        {
            foreach (CrossingRoad road in StartQueue)
            {
                //夜班在  十三号街/全运路就没车接的处理，便乘最近的下一个回库车回库
                if (road._ClassType == ClassType.Night)
                {
                    int index = allTrainInfo.IndexOf(road.Items[road.Items.Count - 1]);

                    Train nextTrain = null; //最近一个回库车
                    if (GetNextGarageTrain(index, ref nextTrain))
                    {
                        //回库处理
                        road.EndTime = nextTrain.EndTime;
                        road._OutPlace = AttendOutPlace.Garage;
                        road.BCBackGarageTrainID = nextTrain.TrainID;
                    }
                }
                else
                {
                    if (road.EndTime == -1)
                        road.EndTime = road.GetLastTrain().EndTime;
                    if (road._OutPlace == AttendOutPlace.UnSeted)
                    {
                        road._OutPlace = AttendOutPlace.FirSta;
                    }
                }


                crossingRoadCollections.Add(road);
            }
            foreach (CrossingRoad road in EndQueue)
            {
                //夜班在 黎明广场/三台子 车的处理，如果没有车子接了，就便乘本车体号的下一车次回库
                if (road._ClassType == ClassType.Night)
                {
                    Train nextTrain = null;
                    int index = allTrainInfo.IndexOf(road.Items[road.Items.Count - 1]);
                    if (CheckLastTrainExists(index, road.GetLastTrain().GetNextTrain(), ref nextTrain))
                    {
                        //回库处理
                        road.EndTime = nextTrain.EndTime;
                        road._OutPlace = AttendOutPlace.Garage;
                        road.BCBackGarageTrainID = nextTrain.TrainID;
                    }
                    
                }
                else
                {
                    if (road.EndTime == -1)
                        road.EndTime = road.GetLastTrain().EndTime;
                    if (road._OutPlace == AttendOutPlace.UnSeted)
                    {
                        //road._OutPlace = AttendOutPlace.LastSta;
                        road._OutPlace = road.GetLastTrain().EndPlace;
                    }
                }
                
                crossingRoadCollections.Add(road);
            }
            foreach (CrossingRoad road in GarageCrossList)
            {
                if (road.EndTime == -1)
                    road.EndTime = road.GetLastTrain().EndTime;
                road._OutPlace = AttendOutPlace.Garage;
                crossingRoadCollections.Add(road);
            }

            crossingRoadCollections.Sort(new CrossRoadCompare());
            log = new WriteLog("testOutPut.txt");

            for (int i = 0; i < crossingRoadCollections.Count; i++)
            {
                CrossingRoad road = crossingRoadCollections[i] as CrossingRoad;
                //for (int k = 0; k < road.Items.Count; k++)
                //{
                //    Train train = road.Items[k] as Train;

                //    SetGroup(ref train, ref road, k);
                //}

                OutPutRoad(road, i.ToString());
            }
            log.Close();
        }

        public void OutPutRoad(CrossingRoad road, string index)
        {
            string stringRunTrain = null;
            for (int i = 0; i < road.Items.Count; i++)
            {
                Train train = road.Items[i] as Train;
                stringRunTrain += train.TrainID + "--->";
            }
            stringRunTrain = stringRunTrain.Substring(0, stringRunTrain.Length - 4); //去除最后一个 “--->”

            string content = "";
            if (road.is_bc_first)
            {
                content += string.Format("(便{0} 十三号街)", road.bc_train.TrainID);
            }
            else if (road.is_bc_last)
            {
                content += string.Format("(便{0} 黎明广场)", road.bc_train.TrainID);
            }
            if (road.is_meal_road)
            {
                content += "(顶饭圈)";
            }
            log.WriteLine(content + string.Format("交路 {0} : {1}", Convert.ToInt32(index) + 1, stringRunTrain));
        }
    }

    class CrossingRoadParameter
    {
        public string lineID { get; set; }

        public int TableID { get; set; }

        public string TableName { get; set; }

        public string FirstID { get; set; }

        public string PhoneOutTrain { get; set; }

        public bool Is_NightMeal_BC { get; set; }

        public string NightEmptyTrain { get; set; }

        public ArrayList UnNightBCOutCollection { get; set; }

        public Dictionary<string, ClassType> UnMorningBcCollection = new Dictionary<string, ClassType>();

        public ObservableCollection<EarlyBackGarageModel> EarlyBackGarageCollections = new ObservableCollection<EarlyBackGarageModel>();

        public ObservableCollection<SetMealCrossRoadModel> SetMealCrossRoadCollection = new ObservableCollection<SetMealCrossRoadModel>();

        public ObservableCollection<TrainIdModel> PhoneAttendOutCollections = new ObservableCollection<TrainIdModel>();

        public ObservableCollection<TrainIdModel> UnplanCollection = new ObservableCollection<TrainIdModel>();

        public ArrayList bc_last_arr { get; set; }

        public ArrayList bc_first_arr { get; set; }

        public int int_ChangeTime_ZB { get; set; }

        public int int_ChangeTime_BB { get; set; }

        public int int_ZB_OutTime { get; set; }

        public int int_ZB_BackTime { get; set; }

        public int int_BB_OutTime { get; set; }

        public int int_LunchTime { get; set; }

        public int int_SuperTime { get; set; }

        public int restTime { get; set; }

        public int mealRestTime { get; set; }

        public int BcUpNum { get; set; }

        public int BcDownNum { get; set; }

        public int lunchCrossRoadCount { get; set; }

        public int supperCrossRoadCount { get; set; }

        public int GarageAhead { get; set; }

        public int GarageBCAhead { get; set; }

        public int NormalAhead { get; set; }

        public int NormalDelay { get; set; }

        public int GarageDelay { get; set; }

        public int BcGarageDelay{get;set;}
    }

    class CrossRoadCompare : IComparer
    {
        public int Compare(object x, object y)
        {
            Train trainX = ((CrossingRoad)x).Items[0] as Train;

            Train trainY = ((CrossingRoad)y).Items[0] as Train;

            return trainX.BeginTime - trainY.BeginTime;
        }
    }

    class QueueCompare : IComparer<CrossingRoad>
    {
        public int Compare(CrossingRoad x, CrossingRoad y)
        {
            if (x.availableTime == -1)
            {
                if (y.availableTime == -1)
                {
                    if ((x.is_bc_first || x.is_bc_last) && (y.is_bc_first || y.is_bc_last))
                    {
                        return x.bc_train.EndTime - y.bc_train.EndTime;
                    }
                    return 0;
                }
                else
                {
                    return -1;
                }
            }
            else
            {
                if (y.availableTime == -1)
                {
                    return 1;
                }
                else
                {
                    if (x.availableTime == y.availableTime)  //顶饭圈司机的排序
                    {
                        if (x.is_meal_road)
                        {
                            if (y.is_meal_road)
                                return 0;
                            else
                                return -1;
                        }
                        else
                        {
                            if (y.is_meal_road)
                                return 1;
                            else
                                return 0;
                        }
                    }
                    return x.availableTime - y.availableTime;
                }
            }

        }
    }
}
